<?php

namespace App\Service\Third;

use App\Helpers\PayUtil;
use App\Helpers\RedisUtil;
use App\Model\PaycallbackLog;
use App\Model\PayOrder;
use App\Model\Service\PaycallbackService;

/**
 * 杉德支付回调
 */
class SandPayCallbackService extends PayBaseService
{
    public function handle()
    {
        $callbackArray = $this->request->all();
        log_info(__CLASS__ . "==" . json_encode($callbackArray['data']));
        //订单号
        $payInfoArray = json_decode($callbackArray['data'], true);
        $outTradeNo = $this->parseOutTradeNo($payInfoArray);

        //锁住该订单处理
        $lockTime = 120;
        $key = "SandPayCallbackService_{$outTradeNo}";
        if (RedisUtil::concurrentLock($key, $lockTime)) {
            log_info(__CLASS__ . "==LastProcessing=={$outTradeNo}");
            return ['result' => 1];
        }

        //记录回调日志
        $record = PayOrder::getByOutTradeNo($outTradeNo);
        if (!$record) return ['result' => 0];
        PaycallbackLog::addRecord($record['channel'], $outTradeNo, $callbackArray);

        //处理订单
        $payMoney = $this->parsePayMoney($payInfoArray);
        PaycallbackService::successCallback($outTradeNo, $payMoney, $record['channel']);
        log_info(__CLASS__ . "==Success=={$outTradeNo}");
    }

    /**
     * 解析支付订单号
     */
    protected function parseOutTradeNo($callbackArray = [])
    {
        return $callbackArray['body']['orderCode'] ?? '';
    }

    /**
     * 解析支付总金额（分）
     */
    protected function parsePayMoney($callbackArray = [])
    {
        return isset($callbackArray['body']['totalAmount']) ? intval($callbackArray['body']['totalAmount']) : 0;
    }
}
